#include "HBBoard.h"
#include <QDebug>
#include <QPainter>

int yLeft = 20;
int xBottom = 20;
int hbRight = 20;
int hbTop = 20;

HBBoard::HBBoard(QWidget* parent)
    : QWidget(parent)
{
}

void HBBoard::configPoints(QList<HBPoint> points)
{
    m_points.clear();
    m_points.append(points);
    m_dealData();
    update();
}

void HBBoard::paintEvent(QPaintEvent* event)
{

    qreal w = width() - yLeft - hbRight; //画画区域宽度
    qreal h = height() - hbTop - xBottom; //画画区域高度

    QPainter painter(this);
    painter.setPen(QPen(Qt::green, 2));
    painter.setBrush(Qt::gray);

    painter.save();
    painter.setPen(QPen(Qt::black, 2));

    m_drawX(painter);
    m_drawY(painter);
    painter.restore();

    painter.drawLines(m_toPoints);
}

void HBBoard::m_drawX(QPainter& painter)
{
    qreal w = width() - yLeft - hbRight; //画画区域宽度

    qreal y = height() - xBottom;
    painter.drawLine(yLeft, y, width() - hbRight, y);

    int num = 5;
    qreal unit = w / (num * 1.0);

    qreal numUnit = (m_maxX - m_minX) / num;

    for (int i = 1; i < num; i++) {

        qreal x = m_minX + unit * i;
        painter.drawLine(x, y, x, y + 5);
        painter.drawText(x, y - 10, QString::number(m_minX + numUnit * i));
    }
}

void HBBoard::m_drawY(QPainter& painter)
{
    qreal h = height() - hbTop - xBottom; //画画区域高度

    painter.drawLine(yLeft, hbTop, yLeft, height() - xBottom);

    int num = 5;
    qreal unit = h / (num * 1.0);

    qreal numUnit = (m_maxY - m_minY) / num;

    for (int i = 1; i < num; i++) {

        qreal y = height() - xBottom - unit * i;
        painter.drawLine(yLeft - 3, y, yLeft, y);
        painter.drawText(yLeft + 5, y, QString::number(m_minY + numUnit * i));
    }
}

void HBBoard::m_dealData()
{
    //计算画画区域
    foreach (HBPoint p, m_points) {

        m_minX = qMin((qreal)p.x, m_minX);
        m_maxX = qMax((qreal)p.x, m_maxX);

        m_minY = qMin((qreal)p.y, m_minY);
        m_maxY = qMax((qreal)p.y, m_maxY);
    }

    //    m_minX -= 20;
    //    m_maxX += 40;

    //    m_minY -= 40;
    //    m_maxY += 10;

    //处理数据
    QVector<QPoint> ar;
    foreach (HBPoint p, m_points) {

        QPoint tmp = m_point(p);
        ar.append(tmp);
        ar.append(tmp);
    }
    ar.removeFirst();
    ar.removeLast();

    m_toPoints.clear();
    m_toPoints.append(ar);
}

QPoint HBBoard::m_point(HBPoint p)
{
    int w = width() - yLeft - hbRight; //画画区域宽度
    int h = height() - hbTop - xBottom; //画画区域高度

    // x,y 座标，一个单元距离代表的值
    qreal xUnit = ((m_maxX - m_minX) * 1.0) / (w * 1.0);
    qreal yUnit = ((m_maxY - m_minY) * 1.0) / (h * 1.0);

    QPoint temp;

    qreal x = (p.x - m_minX) / xUnit + yLeft;
    qreal y = height() - xBottom - (p.y - m_minY) / yUnit;

    temp.setX(x);
    temp.setY(y);

    return temp;
}
